﻿using Client.ServerServices;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace Client
{
    public class ListedGames
    {
        public string Username { get; set; }
        public string Stat { get; set; }
        public string Table { get; set; }

        public ListedGames(string u, string s)
        {
            Username = u;
            Stat = s;
        }
    }
    /// <summary>
    /// Interaction logic for Lobby.xaml
    /// </summary>
    public partial class Lobby : UserControl
    {
        private MainWindow mainWindow;
        public ObservableCollection<ListedGames> ListG { get; set; }

        public Lobby()
        {
            InitializeComponent();
            GetUserStats(Login.username);
            RefreshGames();
        }

        public Lobby(MainWindow mainWindow)
        {
            InitializeComponent();
            this.mainWindow = mainWindow;
            SetMyStats();

            RefreshGames();
        }

        public void RefreshGames()
        {
            RefreshGame.BorderThickness = new Thickness(0);
            RefreshGame.BorderBrush = new SolidColorBrush(Colors.White);
            ServerServices.ListGameRequest listGameReq = new ServerServices.ListGameRequest();
            ///if (UserLevel.Text != "")
            listGameReq.Username = Login.username;
            ServerServices.ListGameServiceResponse response;

            try
            {
                ListG = new ObservableCollection<ListedGames>();
                /*IServerServicesCallback callback = new TwoWayMethods(mainWindow);
                    InstanceContext context = new InstanceContext(callback);
                    using (ServerServicesClient client = new ServerServicesClient(context))
                    {*/

                response = mainWindow.client.ListGameProcess(listGameReq);
                //}
                if (response.Code == 112)
                {
                    GamesList.ItemsSource = null;
                    foreach (Client.ServerServices.Game tables in response.Games)
                    {

                        Label usersName = new Label();
                        usersName.Content = tables.PlayerOne;
                        usersName.FontWeight = FontWeights.Bold;
                        Label usersStats = new Label();
                        //TODO lekérdezni a user statját
                        Dictionary<string, string> usersStatsDic = GetUserStats(tables.PlayerOne);
                        usersStats.Content = "ELO point: " + usersStatsDic["ELO"] + " wins: " + usersStatsDic["win"] + " draws: " + usersStatsDic["draw"] + " loses: " + usersStatsDic["loss"];

                        ListedGames l = new ListedGames(usersName.Content.ToString(), usersStats.Content.ToString());
                        l.Table = tables.GameId;

                        ListG.Add(l);
                        //GamesList.Items.Add(listBoxElement);
                        GamesList.ItemsSource = ListG;
                    }

                    GamesList.IsReadOnly = true;

                }
                else
                {
                    MessageBox.Show("Sikertelen játék frissítés. Hibakód: " + response.Code + " " + response.Message);
                }

            }
            catch (Exception)
            {


            }

        }


        private void SetMyStats()
        {
            Dictionary<string, string> myStats = GetUserStats(Login.username);
            UserLevel.Text = myStats["level"];
            UserLoss.Text = myStats["loss"];
            UserWins.Text = myStats["win"];
            UserEloPoint.Text = myStats["ELO"];
            UserDraw.Text = myStats["draw"];

            UserWelcome.Text = "Welcome " + Login.username + "!";
        }


        private Dictionary<string, string> GetUserStats(String askedPlayer)
        {
            Dictionary<string, string> userStats = new Dictionary<string, string>();
            ServerServices.PlayerStatsRequest playerStatsReq = new ServerServices.PlayerStatsRequest();
            playerStatsReq.Username = Login.username;
            playerStatsReq.OpponentUsername = askedPlayer;
            ServerServices.PlayerStatsServiceResponse response;

            try
            {

                //if (MainWindow.ssc.State == System.ServiceModel.CommunicationState.Faulted)
                //{
                IServerServicesCallback callback = new TwoWayMethods(mainWindow);
                InstanceContext context = new InstanceContext(callback);
                using (ServerServicesClient client = new ServerServicesClient(context))
                {
                    response = client.PlayerStatsProcess(playerStatsReq);
                }
                //}
                //response = MainWindow.ssc.PlayerStatsProcess(playerStatsReq);
                if (response.Code == 113)
                {
                    userStats.Add("level", Convert.ToString(response.Level));
                    userStats.Add("ELO", Convert.ToString(response.ELO));
                    userStats.Add("loss", Convert.ToString(response.Loss));
                    userStats.Add("draw", Convert.ToString(response.Draw));
                    userStats.Add("win", Convert.ToString(response.Win));
                }
            }
            catch (Exception)
            {

            }
            return userStats;
        }

        private void NewGameButton_Click(object sender, RoutedEventArgs e)
        {
            ServerServices.NewGameRequest newGameReq = new ServerServices.NewGameRequest();
            newGameReq.Username = Login.username;
            ServerServices.NewGameServiceResponse response;

            try
            {
                //if (MainWindow.ssc.State == System.ServiceModel.CommunicationState.Faulted)
                //{

                response = mainWindow.client.NewGameProcess(newGameReq);

                // }
                //response = MainWindow.ssc.NewGameProcess(newGameReq);
                if (response.Code == 104)
                {
                    //TODO:
                    mainWindow.SetScreenToGame(response.TableID, true, Login.username, false);
                    //TODO END új játék kezdeményezése HOGYAN?
                    //RefreshGames();

                }
                else
                {
                    MessageBox.Show("Sikertelen új játék generálás. Hibakód: " + response.Code + " " + response.Message);
                }

            }
            catch (Exception)
            {


            }
        }

        private void JoinGameButton_Click(object sender, RoutedEventArgs e)
        {
            if (GamesList.SelectedItem != null)
            {
                string name = ((ListedGames)GamesList.SelectedItem).Username;
                string tableID = ((ListedGames)GamesList.SelectedItem).Table;
                JoinGame(name, tableID);
            }
        }

        private void ListGameJoin_Click(object sender, MouseButtonEventArgs e)
        {
            //String[] nameAndTableID = ((Grid)sender).Name.Split('_');
            //JoinGame(nameAndTableID[1], nameAndTableID[2]);
        }

        private void JoinGame(string requester, string tableID)
        {
            ServerServices.JoinGameRequest joinGameReq = new ServerServices.JoinGameRequest();
            joinGameReq.UserName = Login.username;
            ServerServices.JoinGameServiceResponse response;


            try
            {
                //if (MainWindow.ssc.State == System.ServiceModel.CommunicationState.Faulted)
                //{

                joinGameReq.TableID = tableID;
                response = mainWindow.client.JoinGameProcess(joinGameReq);
                //}
                //joinGameReq.TableID = tableID;
                //response = MainWindow.ssc.JoinGameProcess(joinGameReq);
                if (response.Code == 103)
                {
                    mainWindow.SetScreenToGame(tableID, false, requester, false);
                }
                else
                {
                    MessageBox.Show("Sikertelen a játékba csatlakozás. Hibakód: " + response.Code + " " + response.Message);
                }

            }
            catch (Exception)
            {

            }
        }





        private void LogoutButton_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Biztos ki akarsz lépni a játékból?", "Kilépés a játékból", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                ServerServices.LogoutRequest logoutReq = new ServerServices.LogoutRequest();
                logoutReq.UserName = Login.username;
                ServerServices.LogoutServiceResponse response;

                try
                {
                    //if (MainWindow.ssc.State == System.ServiceModel.CommunicationState.Faulted)
                    //{

                    response = mainWindow.client.LogoutProcess(logoutReq);

                    //}
                    //response = MainWindow.ssc.LogoutProcess(logoutReq);
                    if (response.Code == 111)
                    {
                        Login.username = null;
                        mainWindow.SetScreen("login");

                    }
                    else
                    {
                        MessageBox.Show("Sikertelen kilépés a játékból. Hibakód: " + response.Code + " " + response.Message);
                    }

                }
                catch (Exception)
                {


                }
            }
        }

        private void RefreshGame_Click(object sender, RoutedEventArgs e)
        {
            RefreshGames();
        }



    }
}
